/**
 * @author Fang Lu, fanglupku@gmail.com
 * 2011-4-13
 */
package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;

import persist.APIDB;
import util.StringDealer;
import code.extract.CEConfig;

import dao.entity.QueryPageRelation;
import dao.entity.SegmentEntity;
import dao.filter.PageFilter;

public class QueryPageDao extends BaseDao{
	public static final int JAVA_FILE_FILTER = 1 << 1;
	public static boolean insertQuery(Connection conn, QueryPageRelation rel){
		String sqlString = "insert into query_page (query_id,page_id,rel_index) values(?,?,?)";
		PreparedStatement pstmt;
		try {
			pstmt = conn.prepareStatement(sqlString);
			pstmt.setInt(1, rel.getQuery_id());
			pstmt.setInt(2, rel.getPage_id());
			pstmt.setInt(3, rel.getIndex());
			pstmt.executeUpdate();
			pstmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	public static String getRelMark(int query_id, int page_id){
		return query_id + "-" + page_id;
	}
	public static HashSet<String> getAllRelMarkSet(Connection conn){
		HashSet<String> resultSet = new HashSet<String>();
		String sqlString = "select query_id,page_id from query_page";
		Statement stmt;
		try {
			stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sqlString);
			while (rs.next()){
				int thisQueryID = rs.getInt(1);
				int thisPageID = rs.getInt(2);
				resultSet.add(getRelMark(thisQueryID, thisPageID));
			}
			rs.close();
			stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return resultSet;
	}
	public static ArrayList<QueryPageRelation> getPageListByQueryID(Connection conn, int queryID){
		ArrayList<QueryPageRelation> result = new ArrayList<QueryPageRelation>();
		String sqlString = "select query_id,page_id,rel_index from query_page where query_id=" + queryID;
		try {
			Statement stmt = conn.createStatement();
			ResultSet resultSet = stmt.executeQuery(sqlString);
			while(resultSet.next()){
				int query_id = resultSet.getInt(1);
				int page_id = resultSet.getInt(2);
				int rel_index = resultSet.getInt(3);
				QueryPageRelation thisRel = new QueryPageRelation(query_id, page_id, rel_index);
				result.add(thisRel);
			}
			stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
	public static ArrayList<SegmentEntity> getSegmentListByQueryID(Connection conn, int queryID, int filterType){
		ArrayList<QueryPageRelation> relList = getPageListByQueryID(conn, queryID);
		ArrayList<Integer> pageidList = new ArrayList<Integer>();
		HashSet<Integer> singleSet = new HashSet<Integer>();
		for (int i=0; i<relList.size(); ++i){
			if (!singleSet.contains(relList.get(i).getPage_id())){
				pageidList.add(relList.get(i).getPage_id());
				singleSet.add(relList.get(i).getPage_id());
			}
		}
		if ((filterType & JAVA_FILE_FILTER) != 0){
			pageidList = PageFilter.filterJavaFile(conn, pageidList);
		}
		ArrayList<SegmentEntity> result = SegmentDao.getSegmentListByPageIDList(conn, pageidList, 50);
		return result;
	}
	public static HashMap<Integer, Integer> getPageIDMapQueryID(Connection conn){
		HashMap<Integer, Integer> result = new HashMap<Integer, Integer>();
		String sqlString = "select page_id,query_id from query_page";
		try {
			Statement stmt = conn.createStatement();
			ResultSet resultSet = stmt.executeQuery(sqlString);
			while(resultSet.next()){
				int page_id = resultSet.getInt(1);
				int query_id = resultSet.getInt(2);
				
				result.put(page_id, query_id);
			}
			stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
	public static void initRel(){
		Connection conn = getTestConn();
		APIDB db = new APIDB(CEConfig.getAPIBDBDirname(), 1024 * 1024, "utf8");
		HashMap<String, String> linkMapAPI = db.getLinkMapAPI();
		HashMap<String, Integer> linkMapID = PageDao.getLinkMapID(conn);
		HashMap<String, Integer> APIMapID = APIDao.getNameMapID(conn);
		Iterator<String> itor = linkMapAPI.keySet().iterator();
		int count = 0;
		while(itor.hasNext()){
			String thisLink = itor.next();
			String thisAPI = linkMapAPI.get(thisLink);
//			System.out.println(thisAPI + ":" + thisLink);
			if (linkMapID.containsKey(thisLink)){
				int thisLinkID = linkMapID.get(thisLink);
				int thisAPIID = APIMapID.get(thisAPI);
				QueryPageRelation thisRel = new QueryPageRelation(thisAPIID, thisLinkID, 0);
				insertQuery(conn, thisRel);
				++ count;
				if (count % 1000 == 0){
					System.out.println(count + "/" + linkMapAPI.size());
				}
			}
		}
		
		db.close();
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String args[]){
		//get a test connection, the user and pwd is hardcode.
		Connection conn = getTestConn();
		//get the list of segment by query id, you can get the query id from query table in database(mysql), 
		//3440 is the id of "...BufferedReader..."  
		ArrayList<SegmentEntity> segList = getSegmentListByQueryID(conn, 2, JAVA_FILE_FILTER);
		//get all pageid -> link
		HashMap<Integer, String> pageidMapLink = PageDao.getIDMapLink(conn);
		System.out.println(segList.size());
		int count = 1;
		for (int i=0; i<segList.size(); ++i){
			if (segList.get(i).getType() == SegmentEntity.CODE_SEGMENT ){
				String thisContent = segList.get(i).getContent();
				//trim the beginning empty line, and ending empty line. 
				thisContent = StringDealer.trimEmptyLine(thisContent);
				int thisLineNum = StringDealer.getLineNumber(thisContent);
				if (thisLineNum > 2 && thisLineNum < 100)
				{
					System.out.println("code:" + count + ":pageid:" + segList.get(i).getPage_id()
							+ ":" + pageidMapLink.get(segList.get(i).getPage_id()));
					System.out.println(segList.get(i).getContent());
					
					++count;
				}

			}
		}
	}
}
